'use client';

import { useState, useEffect, Fragment } from 'react';
import { Menu, Transition } from '@headlessui/react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { 
  BellIcon, 
  CheckCircleIcon,
  ChatBubbleLeftEllipsisIcon,
  ExclamationCircleIcon,
  DocumentTextIcon,
  UserGroupIcon,
  CheckIcon,
} from '@heroicons/react/24/outline';
import { Notification, NotificationType } from '@/types/notification';
import { notificationApi } from '@/lib/api';

interface NotificationDropdownProps {
  className?: string;
}

export default function NotificationDropdown({ className }: NotificationDropdownProps) {
  const router = useRouter();
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(true);
  const [isMarkingRead, setIsMarkingRead] = useState(false);

  // 加载通知
  useEffect(() => {
    const loadNotifications = async () => {
      setLoading(true);
      try {
        const data = await notificationApi.getNotifications();
        // 确保data是一个数组
        setNotifications(Array.isArray(data) ? data : []);
      } catch (error) {
        console.error('获取通知失败:', error);
        // 出错时设置为空数组
        setNotifications([]);
      } finally {
        setLoading(false);
      }
    };

    loadNotifications();

    // 实际开发中可以添加定时刷新通知
    const intervalId = setInterval(loadNotifications, 60000); // 每分钟刷新一次
    return () => clearInterval(intervalId);
  }, []);

  // 处理查看通知
  const handleViewNotification = async (notification: Notification) => {
    if (!notification.read) {
      try {
        await notificationApi.markAsRead(notification.id);
        setNotifications(prev =>
          prev.map(n => (n.id === notification.id ? { ...n, read: true } : n))
        );
      } catch (error) {
        console.error('标记通知已读失败:', error);
      }
    }
    
    if (notification.actionUrl) {
      router.push(notification.actionUrl);
    }
  };

  // 处理标记所有为已读
  const handleMarkAllAsRead = async () => {
    if (isMarkingRead) return;

    setIsMarkingRead(true);
    try {
      await notificationApi.markAllAsRead();
      setNotifications(prev => prev.map(n => ({ ...n, read: true })));
    } catch (error) {
      console.error('标记所有通知已读失败:', error);
    } finally {
      setIsMarkingRead(false);
    }
  };

  // 获取通知图标
  const getNotificationIcon = (type: NotificationType) => {
    switch (type) {
      case NotificationType.TASK_ASSIGNED:
      case NotificationType.TASK_COMPLETED:
        return <CheckCircleIcon className="h-5 w-5 text-blue-500" />;
      case NotificationType.TASK_COMMENTED:
      case NotificationType.MENTION:
        return <ChatBubbleLeftEllipsisIcon className="h-5 w-5 text-green-500" />;
      case NotificationType.TASK_DUE_SOON:
        return <ExclamationCircleIcon className="h-5 w-5 text-amber-500" />;
      case NotificationType.PROJECT_INVITATION:
      case NotificationType.PROJECT_UPDATE:
      case NotificationType.TEAM_JOIN:
        return <UserGroupIcon className="h-5 w-5 text-purple-500" />;
      case NotificationType.DOCUMENT_SHARED:
        return <DocumentTextIcon className="h-5 w-5 text-gray-500" />;
      default:
        return <BellIcon className="h-5 w-5 text-gray-500" />;
    }
  };

  // 格式化时间
  const formatTime = (date: Date | string | null | undefined) => {
    if (!date) return '';
    
    try {
      const now = new Date();
      const dateObj = date instanceof Date ? date : new Date(date);
      const diff = Math.floor((now.getTime() - dateObj.getTime()) / 1000); // 秒
      
      if (diff < 60) return '刚刚';
      if (diff < 3600) return `${Math.floor(diff / 60)}分钟前`;
      if (diff < 86400) return `${Math.floor(diff / 3600)}小时前`;
      if (diff < 2592000) return `${Math.floor(diff / 86400)}天前`;
      
      return dateObj.toLocaleDateString('zh-CN');
    } catch (error) {
      console.error('格式化时间错误:', error);
      return '未知时间';
    }
  };

  // 计算未读通知数量
  const unreadCount = Array.isArray(notifications) ? notifications.filter(n => !n.read).length : 0;

  return (
    <div className={className}>
      <Menu as="div" className="relative inline-block text-left">
        <div>
          <Menu.Button className="relative flex items-center p-1 rounded-full text-gray-600 hover:text-gray-800 focus:outline-none">
            <span className="sr-only">查看通知</span>
            <BellIcon className="h-6 w-6" />
            {unreadCount > 0 && (
              <span className="absolute top-0 right-0 block h-2 w-2 rounded-full bg-red-500 ring-2 ring-white" />
            )}
          </Menu.Button>
        </div>

        <Transition
          as={Fragment}
          enter="transition ease-out duration-100"
          enterFrom="transform opacity-0 scale-95"
          enterTo="transform opacity-100 scale-100"
          leave="transition ease-in duration-75"
          leaveFrom="transform opacity-100 scale-100"
          leaveTo="transform opacity-0 scale-95"
        >
          <Menu.Items className="absolute right-0 mt-2 w-80 origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
            <div className="py-2">
              <div className="px-4 py-2 border-b border-gray-100">
                <div className="flex justify-between items-center">
                  <h3 className="text-sm font-semibold text-gray-900">通知</h3>
                  {unreadCount > 0 && (
                    <button
                      type="button"
                      onClick={handleMarkAllAsRead}
                      disabled={isMarkingRead}
                      className="text-xs text-blue-600 hover:text-blue-800 flex items-center"
                    >
                      <CheckIcon className="h-3 w-3 mr-1" />
                      全部标记为已读
                    </button>
                  )}
                </div>
              </div>
              
              <div className="max-h-64 overflow-y-auto">
                {loading ? (
                  <div className="px-4 py-3 text-sm text-gray-500 text-center">
                    加载中...
                  </div>
                ) : notifications.length === 0 ? (
                  <div className="px-4 py-6 text-sm text-gray-500 text-center">
                    没有通知
                  </div>
                ) : (
                  notifications.map((notification) => (
                    <Menu.Item key={notification.id}>
                      {({ active }) => (
                        <button
                          className={`${
                            active ? 'bg-gray-50' : ''
                          } ${
                            !notification.read ? 'bg-blue-50' : ''
                          } w-full text-left px-4 py-3 flex items-start`}
                          onClick={() => handleViewNotification(notification)}
                        >
                          <div className="flex-shrink-0 mt-0.5 mr-3">
                            {getNotificationIcon(notification.type)}
                          </div>
                          <div className="min-w-0 flex-1">
                            <p className={`text-sm font-medium ${!notification.read ? 'text-gray-900' : 'text-gray-700'}`}>
                              {notification.title}
                            </p>
                            <p className="mt-1 text-sm text-gray-500 line-clamp-2">
                              {notification.content}
                            </p>
                            <p className="mt-1 text-xs text-gray-400">
                              {formatTime(notification.createdAt)}
                            </p>
                          </div>
                        </button>
                      )}
                    </Menu.Item>
                  ))
                )}
              </div>
              
              <div className="border-t border-gray-100 px-4 py-2">
                <Link 
                  href="/notifications"
                  className="block text-center text-xs text-blue-600 hover:text-blue-800"
                >
                  查看全部通知
                </Link>
              </div>
            </div>
          </Menu.Items>
        </Transition>
      </Menu>
    </div>
  );
} 